package com.zgzg.shop.pay.base.utils;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @description: 编程式事务工具类
 * @author: yyqiang
 * @Copyright: Copyright (c) 浙江日报
 * @date: 2022/12/28 15:07
 * @version: 1.0.0
 */
@Slf4j
public class TransactionManager {

    private static final PlatformTransactionManager platformTransactionManager = SpringUtil.getBean(PlatformTransactionManager.class);

    public static <T> boolean execute(Consumer<T> consumer) {
        TransactionStatus status = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            consumer.accept(null);
            platformTransactionManager.commit(status);
            return true;
        } catch (Exception e) {
            platformTransactionManager.rollback(status);
            log.error("编程式事务业务异常回滚", e);
            return false;
        }
    }

    public static boolean execute(Runnable runnable) {
        TransactionStatus status = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            runnable.run();
            platformTransactionManager.commit(status);
            return true;
        } catch (Exception e) {
            platformTransactionManager.rollback(status);
            log.error("编程式事务业务异常回滚", e);
            return false;
        }
    }

    public static <T, R> R execute(Function<T, R> function) {
        TransactionStatus status = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            R result = function.apply(null);
            platformTransactionManager.commit(status);
            return result;
        } catch (Exception e) {
            platformTransactionManager.rollback(status);
            log.error("编程式事务业务异常回滚", e);
            return null;
        }
    }
}
